package org.example;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class NioServer {

    private static final List<SocketChannel> socketChannels = new ArrayList<>();

    public static void main(String[] args) throws Exception {
        //创建NIO ServerSocketChannel, 与BIO的ServerSocket类似
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(9000));
        //设置ServerSocketChannel 为非阻塞
        serverSocketChannel.configureBlocking(false);

        System.out.println("服务启动成功");

        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel != null) {
                System.out.println("链接成功");
                //设置SocketChannel为非阻塞
                socketChannel.configureBlocking(false);
                //将所有客户端连接存放到list中
                socketChannels.add(socketChannel);
            }
            //遍历连接进行数据读取
            Iterator<SocketChannel> iterator = socketChannels.iterator();
            while (iterator.hasNext()) {
                SocketChannel sc = iterator.next();
                ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                //非阻塞模式read方法不会阻塞，否则会阻塞
                int len = sc.read(byteBuffer);
                //如果有数据，把数据打印出来
                if (len > 0) {
                    System.out.println("接收到消息：" + new String(byteBuffer.array()));
                } else if (len == -1) {
                    iterator.remove();
                    System.out.println("客户端端口连接");
                }
            }
        }
    }
}
